在開發規範會議中,我們曾討論「如何具體落實團隊的開發流程規範」,其中一個具體做法就是使用 Git Hook:
在 commit 前,自動執行檢查流程,以確保程式品質與團隊一致性。
Git Hook 是一組可以掛載在 Git 生命週期上的腳本,用來執行自定任務。
例如:在你 commit、push、merge、checkout 等動作時,自動執行檢查邏輯。
Git 預設提供一組 hook 檔案範例放在 .git/hooks/
當你建立指定名稱的腳本檔(如 pre-commit、commit-msg)並加上可執行權限時,Git 就會在對應事件發生時自動執行該腳本
假設我們要落實 Conventional Commits 規範,以下是一個 commit-msg hook 的範例。
mkdir -p scripts
touch scripts/commit-msg
chmod +x scripts/commit-msg
#!/bin/sh
COMMIT_MSG_FILE=$1
COMMIT_MSG=$(head -n 1 "$COMMIT_MSG_FILE")
HEADER_PATTERN="^(feat|fix|docs|style|refactor|test|chore)(\\(.+\\))?: .{1,100}$"
if ! echo "$COMMIT_MSG" | grep -qE "$HEADER_PATTERN"; then
echo "Commit message 不符合 Conventional Commit 格式"
echo "格式應為:type(scope): subject"
echo "其中 type 可為 feat, fix, docs, style, refactor, test, chore"
echo "範例:feat(auth): add user authentication"
exit 1
fi
你可以手動安裝,或使用工具自動安裝(建議使用工具,團隊共享時更方便)。
將 scripts/commit-msg 複製到 .git/hooks/ 目錄:
cp scripts/commit-msg .git/hooks/commit-msg
chmod +x .git/hooks/commit-msg
git commit -m "update user logic"
輸出錯誤訊息:
Commit message 不符合 Conventional Commit 格式
格式應為:type(scope): subject
有興趣的話可以參考 Git 官方 Hook 文件:
🔗 https://git-scm.com/docs/githooks